/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if (root->left == nullptr && root->right == nullptr)
            return root->val;
        return dfs(root, root->val, 1);
    }

    int dfs(TreeNode* root, int last, int times)
    {
        if (root->left == nullptr && root->right == nullptr)
            return root->val + last;

        int cur;
        if (times > 1)
            cur = (last + root->val) * 10;
        else
            cur = last * 10;

        int l = 0, r = 0;


        if (root->left != nullptr)
            l = dfs(root->left, cur, times + 1);
        if (root->right != nullptr)
            r = dfs(root->right, cur, times + 1);

        return l + r;

    }

};